﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;
using PSE.Framework.ErrorLogging;
using PSE.Updater.Client.UI;
using PSE.Updater.Common.Configurations.Server;
using PSE.Updater.Common.Gateway.DataContract;
using PSE.Updater.Common.Providers;
using PSE.Updater.Common.Providers.Interfaces;

namespace TesteUpdater
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            PSE.Updater.Server.Engine.UpdateService.Instance.Initialize();
            Initialize();
        }

        private void Initialize()
        {
            tvwItems.Visible = false;
            tvwItems.Nodes.Clear();

            TreeNode nodeRoot = new TreeNode();
            nodeRoot.Text = "Updater";

            var section = UpdateProviders.Instance.GetSection();
            foreach (ProductConfigurationElement product in section.Products)
            {
                TreeNode nodeProduct = new TreeNode();
                nodeProduct.Text = string.Format("Produto: {0}", product.Name);
                foreach (ProviderConfigurationElement provider in product.Providers)
                {
                    TreeNode nodeProvider = new TreeNode();
                    nodeProvider.Text = string.Format("Provider: {0}", provider.Type);
                    foreach (WatcherConfigurationElement observer in provider.Watchers)
                    {
                        TreeNode nodeObserver = new TreeNode();
                        nodeObserver.Text = string.Format("Directory: {0}", observer.DirectoryTemplate);

                        TreeNode nodeExtensionsFilter = new TreeNode();
                        nodeExtensionsFilter.Text = string.Format("ExtensionsFilter: {0}", observer.ExtensionsFilter);
                        nodeObserver.Nodes.Add(nodeExtensionsFilter);

                        TreeNode nodeRecursive = new TreeNode();
                        nodeRecursive.Text = string.Format("Recursive: {0}", observer.Recursive);
                        nodeObserver.Nodes.Add(nodeRecursive);

                        nodeProvider.Nodes.Add(nodeObserver);
                    }

                    TreeNode nodeCache = new TreeNode();
                    nodeCache.Text = "Cache";
                    IList<IFileDetails> files = PSE.Updater.Server.Engine.UpdateService.Instance.ListFiles(provider.Type, product.Name);
                    foreach (IFileDetails file in files)
                    {

                        TreeNode nodeFile = new TreeNode();
                        nodeFile.Text = string.Format("File: {0}", file.FilePath);

                        TreeNode nodeModule = new TreeNode();
                        nodeModule.Text = string.Format("ModuleName: {0}", file.ModuleName);
                        nodeFile.Nodes.Add(nodeModule);

                        TreeNode nodeSize = new TreeNode();
                        nodeSize.Text = string.Format("Size: {0}", file.Size);
                        nodeFile.Nodes.Add(nodeSize);

                        TreeNode nodeStatus = new TreeNode();
                        nodeStatus.Text = string.Format("Status: {0}", file.Status);
                        nodeFile.Nodes.Add(nodeStatus);


                        TreeNode nodePackageType = new TreeNode();
                        nodePackageType.Text = " - ";
                        if (file.FilePackageType.HasValue)
                            nodePackageType.Text = string.Format("PackageType: {0}", file.FilePackageType.Value.ToString());

                        nodeFile.Nodes.Add(nodePackageType);

                        TreeNode nodeUpdateDescription = new TreeNode();
                        nodeUpdateDescription.Text = string.Format("UpdateDescription: {0}", file.UpdateDescription);
                        nodeFile.Nodes.Add(nodeUpdateDescription);

                        TreeNode nodeVersion = new TreeNode();
                        nodeVersion.Text = string.Format("Version: {0}", file.Version);
                        nodeFile.Nodes.Add(nodeVersion);

                        nodeCache.Nodes.Add(nodeFile);
                    }
                    nodeProvider.Nodes.Add(nodeCache);

                    nodeProduct.Nodes.Add(nodeProvider);
                }
                nodeRoot.Nodes.Add(nodeProduct);
            }
            tvwItems.Nodes.Add(nodeRoot);

            tvwItems.ExpandAll();
            tvwItems.Visible = true;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            Initialize();
        }

        protected override void OnClosed(EventArgs e)
        {
            PSE.Updater.Server.Engine.UpdateService.Instance.Terminate();
            base.OnClosed(e);
        }

        private void btnVerificar_Click(object sender, EventArgs e)
        {
            Verificar();
        }

        private void Verificar()
        {
            lstArquivos.Items.Clear();

            if (string.IsNullOrEmpty(txtSistema.Text))
            {
                MessageBox.Show("Informe o Sistema");
                txtSistema.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtModulo.Text))
            {
                MessageBox.Show("Informe o Módulo");
                txtModulo.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtVersao.Text))
            {
                MessageBox.Show("Informe a Versão");
                txtVersao.Focus();
                return;
            }   

            List<ModuleVersion> modules = new List<ModuleVersion>();
            modules.Add(new ModuleVersion
                {
                    SystemName = txtSistema.Text,
                    ModuleName = txtModulo.Text,
                    Version = txtVersao.Text
                }
            );

            var items =
            PSE.Updater.Server.Engine.UpdateService.Instance.GetAvailableUpdates(ProviderType.Updates, modules);

            if (items.Count > 0)
            {
                foreach (var item in items)
                    lstArquivos.Items.Add(string.Format("{0} - {1} - {2}", item.Version, item.FilePackageType.Value, item.Status));
            }
            else
            {
                lstArquivos.Items.Add("Sem atualizações disponíveis...");
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
